package com.net.oil.oilWear;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.net.oil.R;
import com.net.oil.base.BaseActivity;
import com.net.oil.oilWear.bean.FillOilRecordBean;
import com.net.oil.oilWear.contract.AddOilWearContract;
import com.net.oil.oilWear.presenter.AddOilWearPresenter;
import com.net.oil.util.DateFormat;

import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AddOilWearActivity extends BaseActivity<AddOilWearPresenter> implements AddOilWearContract.View {

    private String TAG = AddOilWearActivity.class.getName();

    public static final String IntentCarId = "intent_car_id";       //添加记录时，传入的车辆id
    public static final String IntentRecord = "intent_record";      //修改记录时，传入记录的key
    public static final String IntentType = "intent_type";          //类型ADD_TYPE， EDIT的key
    public static final int ADD_TYPE = 0;       //添加记录
    public static final int EDIT = 1;           //修改记录

    @BindView(R.id.toolbar_go_back)
    ImageView toolbarGoBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_save)
    TextView toolbarSave;
    @BindView(R.id.date_tv)
    TextView dateTv;
    @BindView(R.id.date_select_ly)
    RelativeLayout dateSelectLy;
    @BindView(R.id.mileage_et)
    EditText mileageEt;
    @BindView(R.id.add_oil_money_et)
    EditText addOilMoneyEt;
    @BindView(R.id.oil_price_et)
    EditText oilPriceEt;
    @BindView(R.id.add_oil_amount_et)
    EditText addOilAmountEt;

    private DatePicker datePicker;

    private int carId = -1;

    private int type = ADD_TYPE;        //默认类型为添加记录

    FillOilRecordBean.ListBean bean;


    private boolean oilMoneyFirst = false;
    private boolean priceFirst = false;
    private boolean oilAmountFirst = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_oil_wear);
        ButterKnife.bind(this);
        presenter = new AddOilWearPresenter(this);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            type = getIntent().getExtras().getInt(IntentType, ADD_TYPE);
            if (type == ADD_TYPE) {
                carId = getIntent().getIntExtra(IntentCarId, -1);
            } else if (type == EDIT) {
                bean = (FillOilRecordBean.ListBean) getIntent().getExtras().getSerializable(IntentRecord);
            }
        }
        initView();
    }

    private void initView() {
        toolbarTitle.setText("添加记录");

        if (type == EDIT) {
            dateSelectLy.setEnabled(false);
            if (bean != null) {
                /* 加油时间 yyyy-mm-dd */
                dateTv.setText(DateFormat.formatDateTime(bean.getT(), DateFormat.FormatFlag.YDM));
                /* 里程 */
                mileageEt.setText(String.valueOf(bean.getCurrentMileage()));
                /* 加油花费的总金额 */
                addOilMoneyEt.setText(String.valueOf(bean.getOilMoney()));
                /* 加油油价 */
                oilPriceEt.setText(String.valueOf(bean.getOilPrice()));
                /* 加油升数 */
                addOilAmountEt.setText(String.valueOf(bean.getQuantity()));
            }
        }

        addOilMoneyEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (TextUtils.isEmpty(oilPriceEt.getText().toString()) && TextUtils.isEmpty(addOilAmountEt.getText().toString())){
                    oilMoneyFirst = true;
                }

                if (!TextUtils.isEmpty(s.toString()) && addOilMoneyEt.hasFocus()){
                    double oilMoneyValue = Double.parseDouble(s.toString());
                    if (priceFirst || oilMoneyFirst){
                        String etValue = oilPriceEt.getText().toString();
                        if (!TextUtils.isEmpty(etValue)){
                            double priceValue = Double.parseDouble(etValue);
                            addOilAmountEt.setText(doubleToString(oilMoneyValue / priceValue));
                        }
                    }else if (oilAmountFirst){
                        String etValue  = addOilAmountEt.getText().toString();
                        if (!TextUtils.isEmpty(etValue)) {
                            double oilAmountValue = Double.parseDouble(etValue);
                            oilPriceEt.setText(doubleToString(oilMoneyValue / oilAmountValue));
                        }
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        oilPriceEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (TextUtils.isEmpty(addOilAmountEt.getText().toString()) && TextUtils.isEmpty(addOilMoneyEt.getText().toString())){
                    priceFirst = true;
                }

                if (!TextUtils.isEmpty(s.toString()) && oilPriceEt.hasFocus()){
                    double priceValue = Double.parseDouble(s.toString());
                    if (oilMoneyFirst || priceFirst){
                        String etValue = addOilMoneyEt.getText().toString();
                        if (!TextUtils.isEmpty(etValue)){
                            double oilMoneyValue = Double.parseDouble(etValue);
                            addOilAmountEt.setText(doubleToString(oilMoneyValue / priceValue));
                        }
                    }else if (oilAmountFirst){
                        String etValue = addOilAmountEt.getText().toString();
                        if (!TextUtils.isEmpty(etValue)){
                            double oilAmountValue = Double.parseDouble(etValue);
                            addOilMoneyEt.setText(doubleToString(priceValue * oilAmountValue));
                        }
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        addOilAmountEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (TextUtils.isEmpty(addOilMoneyEt.getText().toString()) && TextUtils.isEmpty(oilPriceEt.getText().toString())){
                    oilAmountFirst = true;
                }

                if (!TextUtils.isEmpty(s.toString()) && addOilAmountEt.hasFocus()){
                    double oilAmountValue = Double.parseDouble(s.toString());
                    if (oilMoneyFirst){
                        String etValue = addOilMoneyEt.getText().toString();
                        if (!TextUtils.isEmpty(etValue)){
                            double addOilMoneyValue = Double.parseDouble(etValue);
                            oilPriceEt.setText(doubleToString(addOilMoneyValue / oilAmountValue));
                        }
                    }else if (priceFirst || oilAmountFirst){
                        String etValue = oilPriceEt.getText().toString();
                        if (!TextUtils.isEmpty(etValue)){
                            double oilPriceValue = Double.parseDouble(etValue);
                            addOilMoneyEt.setText(doubleToString(oilPriceValue * oilAmountValue));
                        }
                    }
                }

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    /**
     * 添加加油记录成功
     */
    @Override
    public void addFillOilRecordSuccess() {
        Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
        setResult(RESULT_OK);
        finish();
    }

    /**
     * 添加加油记录失败
     */
    @Override
    public void addFillOilRecordFailed() {
    }

    /**
     * 编辑加油记录成功
     */
    @Override
    public void updateFillOilRecordSuccess() {
        Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
        setResult(RESULT_OK);
        finish();
    }

    /**
     * 编辑加油记录失败
     */
    @Override
    public void updateFillOilRecordFailed() {
    }

    @OnClick({R.id.toolbar_go_back, R.id.toolbar_save, R.id.date_select_ly})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.toolbar_go_back:
                finish();
                break;
            case R.id.toolbar_save:
                addRecord();
                break;
            case R.id.date_select_ly:
                showDateSelectDialog();
                break;
        }
    }

    private void addRecord() {
        String date = dateTv.getText().toString();
        if (TextUtils.isEmpty(date)) {
            Toast.makeText(this, "请输入加油日期", Toast.LENGTH_SHORT).show();
            return;
        }
        String mileage = mileageEt.getText().toString();
        if (TextUtils.isEmpty(mileage)) {
            Toast.makeText(this, "请输入最新里程", Toast.LENGTH_SHORT).show();
            return;
        }
        String addOilMoney = addOilMoneyEt.getText().toString();
        if (TextUtils.isEmpty(addOilMoney)) {
            Toast.makeText(this, "请输入加油金额", Toast.LENGTH_SHORT).show();
            return;
        }
        String oilPrice = oilPriceEt.getText().toString();
        if (TextUtils.isEmpty(oilPrice)) {
            Toast.makeText(this, "请输入单价", Toast.LENGTH_SHORT).show();
            return;
        }
        String addOilAmount = addOilAmountEt.getText().toString();
        if (TextUtils.isEmpty(addOilAmount)) {
            Toast.makeText(this, "请输入加油量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (type == ADD_TYPE) {
            presenter.addFillOilRecord(carId, Integer.parseInt(mileage), Double.parseDouble(addOilAmount),
                    Double.parseDouble(oilPrice), Double.parseDouble(addOilMoney), date);
        } else if (type == EDIT) {
            if (bean != null) {
                presenter.updateFillOilRecord(bean.getId(), Integer.parseInt(mileage), Double.parseDouble(addOilAmount),
                        Double.parseDouble(oilPrice), Double.parseDouble(addOilMoney));
            }
        }

    }


    private void showDateSelectDialog() {

        View view = View.inflate(this, R.layout.date_select, null);
        datePicker = view.findViewById(R.id.date_pick);
        datePicker.setMaxDate(new Date().getTime());

        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.DialogButtonTheme);
        builder.setTitle("加油时间");
        builder.setView(view);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());
                String date = DateFormat.getStringDateByCalendar(calendar);
                dateTv.setText(date);
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    private String doubleToString(double value) {
        DecimalFormat decimalFormat = new DecimalFormat();
        decimalFormat.setMaximumFractionDigits(2);
        return decimalFormat.format(value);
    }


}
